<template>
  <p>
    <button @click="add" class="btn btn-white btn-default">
      <i class="ace-icon fa fa-edit"></i>
      新增
    </button>
    &nbsp;
    <button @click="refresh" class="btn btn-white btn-default">
      <i class="ace-icon fa fa-undo"></i>
      刷新
    </button>
  </p>

  <div class="row">
    <div v-for="course in courses" class="col-md-3">
      <div class="thumbnail search-thumbnail">
        <img v-show="!course.image" class="media-object" src="/static/image/demo-course.jpg"/>
        <img v-show="course.image" class="media-object" :src="course.image"/>
        <div class="caption">
          <div class="clearfix">
            <span class="pull-right label label-primary info-label">
              {{ optionKV(COURSE_LEVEL_REF, course.level) }}
            </span>
            <span class="pull-right label label-primary info-label">
              {{ optionKV(COURSE_CHARGE_REF, course.charge) }}
            </span>
            <span class="pull-right label label-primary info-label">
              {{ optionKV(COURSE_STATUS_REF, course.status) }}
            </span>
          </div>
          <h3 class="search-title">
            <a href="#" class="blue">{{ course.name }}</a>
          </h3>

          <!-- 导师 过滤出匹配的 -->
          <div v-for="teacher in teachers.filter((t)=>{return t.id === course.teacherId})" class="profile-activity clearfix">
            <div>
              <img class="pull-left" src="/static/image/讲师头像/头像1.jpg">
              <a class="user" href="#">{{ teacher.name }}</a>
              <br>
              {{ teacher.position }}
            </div>
          </div>

          <p>
            <span class="blue bolder bigger-150">{{ course.price }}&nbsp;<i class="fa fa-rmb"></i></span>
          </p>
          <p>
            {{ course.summary }}
          </p>
          <p>
            <span class="badge badge-info">{{ course.id }}</span>
            <span class="badge badge-info">排序：{{ course.sort }}</span>
            <span class="badge badge-info">时长：{{ formatSecond(course.time) }}</span>
          </p>
          <p>
            <button v-on:click="edit(course)" class="btn btn-white btn-xs btn-info btn-round">
              编辑
            </button>
            &nbsp;
            <button v-on:click="toContent(course)" class="btn btn-white btn-xs btn-info btn-round">
              内容
            </button>
            &nbsp;
            <button v-on:click="openSortModal(course)" class="btn btn-white btn-xs btn-info btn-round">
              排序
            </button>
            &nbsp;
            <button v-on:click="toChapter(course)" class="btn btn-white btn-xs btn-info btn-round">
              大章
            </button>
            &nbsp;
            <button v-on:click="del(course)" class="btn btn-white btn-xs btn-info btn-round">
              删除
            </button>
          </p>
        </div>
      </div>
    </div>
  </div>

  <!-- 分页插件 -->
  <pagination ref="paginationRef" :list="getCourseList" />

  <!-- 课程编辑 新增 -->
  <div class="modal fade" id="form-modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
          <h4 class="modal-title" id="myModalLabel">表单</h4>
        </div>
        <div class="modal-body">
          <form class="form-horizontal">
            <div class="form-group">
              <label class="col-sm-2 control-label">分类</label>
              <div class="col-sm-10">
                <ul id="tree" class="ztree"></ul>
              </div>
            </div>
            <div class="form-group">
              <label class="col-sm-2 control-label">名称</label>
              <div class="col-sm-10">
                <input v-model="course.name" type="text" class="form-control">
              </div>
            </div>
            <div class="form-group">
              <label class="col-sm-2 control-label">封面</label>
              <div class="col-sm-10">
                <BigFile
                    :suffixs="['jpg', 'jpeg', 'png']"
                    text="上传封面"
                    :afterUpload="afterUpload"
                    :input-id="'image-upload'"
                    :use="FILE_TYPE.COURSE.key">
                </BigFile>
                <!-- 封面预览 -->
                <div v-show="course.image" class="row">
                  <div class="col-md-5">
                    <img :src="course.image" class="img-responsive">
                  </div>
                </div>
              </div>
            </div>
            <div class="form-group">
              <label class="col-sm-2 control-label">讲师</label>
              <div class="col-sm-10">
                <select v-model="course.teacherId" class="form-control">
                  <option v-for="o in teachers" :value="o.id">{{ o.name }}</option>
                </select>
              </div>
            </div>
            <div class="form-group">
              <label class="col-sm-2 control-label">概述</label>
              <div class="col-sm-10">
                <input v-model="course.summary" type="text" class="form-control">
              </div>
            </div>
            <div class="form-group">
              <label class="col-sm-2 control-label">时长</label>
              <div class="col-sm-10">
                <input v-model="course.time" type="text" class="form-control">
              </div>
            </div>
            <div class="form-group">
              <label class="col-sm-2 control-label">价格（元）</label>
              <div class="col-sm-10">
                <input v-model="course.price" type="text" class="form-control">
              </div>
            </div>
            <div class="form-group">
              <label class="col-sm-2 control-label">级别</label>
              <div class="col-sm-10">
                <select v-model="course.level" class="form-control">
                  <option v-for="o in COURSE_LEVEL_REF" :value="o.key">{{ o.value }}</option>
                </select>
              </div>
            </div>
            <div class="form-group">
              <label class="col-sm-2 control-label">收费</label>
              <div class="col-sm-10">
                <select v-model="course.charge" class="form-control">
                  <option v-for="o in COURSE_CHARGE_REF" :value="o.key">{{ o.value }}</option>
                </select>
              </div>
            </div>
            <div class="form-group">
              <label class="col-sm-2 control-label">状态</label>
              <div class="col-sm-10">
                <select v-model="course.status" class="form-control">
                  <option v-for="o in COURSE_STATUS_REF" :value="o.key">{{ o.value }}</option>
                </select>
              </div>
            </div>
            <div class="form-group">
              <label class="col-sm-2 control-label">报名数</label>
              <div class="col-sm-10">
                <input v-model="course.enroll" type="text" class="form-control">
              </div>
            </div>
            <div class="form-group">
              <label class="col-sm-2 control-label">顺序</label>
              <div class="col-sm-10">
                <input v-model="course.sort" type="text" class="form-control" disabled>
              </div>
            </div>
          </form>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
          <button @click="saveCourse" type="button" class="btn btn-primary">保存</button>
        </div>
      </div>
    </div>
  </div>

  <!-- 课程很多 自动排序 -->
  <div class="modal fade" id="course-sort-modal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
          <h4 class="modal-title">排序</h4>
        </div>
        <div class="modal-body">
          <form class="form-horizontal">
            <div class="form-group">
              <label class="col-sm-2 control-label">当前排序</label>
              <div class="col-sm-9">
                <input class="form-control" disabled v-model="sort.oldValue">
              </div>
            </div>
            <div class="form-group">
              <label class="col-sm-2 control-label">新排序</label>
              <div class="col-sm-9">
                <input class="form-control" v-model="sort.newValue">
              </div>
            </div>
          </form>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-white btn-info btn-round" data-dismiss="modal">取消</button>
          <button type="button" class="btn btn-white btn-info btn-round" @click="updateSort()">更新排序</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import {onMounted, ref} from "vue";
import pagination from "@/components/pagination";
import Filter from "@/filter/filter"
import {useRouter} from "vue-router";
import BigFile from "@/components/big-file";

export default {
  name: "Course",
  components: {
    pagination,
    BigFile
  },
  setup() {
    // courses 数组
    const courses = ref([]);
    const course = ref({}); // 保存课程表单
    const paginationRef = ref(null);

    const categorys = ref([]); // 分类数据
    const checkedCategorys = ref([]); // 勾选的分类

    const teachers = ref([]); // 讲师

    const tree = ref(); // 分类树

    const sort = ref({ // 课程排序
      oldValue: 0,
      newValue: 0,
      id: '',
    })

    // 路由
    const router = useRouter();

    // 枚举字段
    const COURSE_LEVEL_REF = ref();
    const COURSE_CHARGE_REF = ref();
    const COURSE_STATUS_REF = ref();

    const FILE_TYPE = FILE_USE; // 文件类型

    // 刷新
    const refresh = () => {
      getCourseList(1);
    }

    // 获取课程列表
    const getCourseList = (page) => {
      Loading.show();
      axios.post(process.env.VUE_APP_SERVER + "/business/admin/course/list",
          {
            page: page,
            size: paginationRef.value.size
          }
      ).then((response) => {
        Loading.hide();
        const resp = response.data;
        courses.value = resp.content.list;
        paginationRef.value.render(page, resp.content.total);
      })
    }

    // 获取课程分类列表
    const listCategory = (courseId) => {
      Loading.show();
      axios.post(process.env.VUE_APP_SERVER + "/business/admin/course/list-category/" + courseId
      ).then((response) => {
        Loading.hide();
        const resp = response.data;
        let list = resp.content;

        // 勾选查询到的分类
        tree.value.checkAllNodes(false);
        for (let i = 0; i < list.length; i++) {
          let node = tree.value.getNodeByParam('id', list[i].categoryId);
          tree.value.checkNode(node, true);
        }
      })
    }

    // 保存课程
    const saveCourse = () => {
      // 保存参数校验
      if ( 1 != 1
                || !Validator.require(course.value.name, "名称")
                || !Validator.length(course.value.name, "名称", 1, 50)
                || !Validator.length(course.value.summary, "概述", 1, 2000)
                || !Validator.length(course.value.image, "封面", 1, 100)
        )
      {
        return;
      }

      // 保存分类
      checkedCategorys.value = tree.value.getCheckedNodes(); // 获取选择的分类
      if (Tool.isEmpty(checkedCategorys.value)) {
        Toast.warning("请选择分类数据！");
        return;
      }
      course.value.categorys = checkedCategorys;

      Loading.show();
      axios.post(process.env.VUE_APP_SERVER + "/business/admin/course/save", course.value).then((response) => {
        const resp = response.data;
        if (resp.success) {
          Loading.hide();
          $('#form-modal').modal('hide');
          Toast.success("保存成功");
          getCourseList(1);
        } else {
          Loading.hide();
          $('#form-modal').modal('hide');
          Toast.warning(resp.message);
        }
      })
    }

    // 删除课程
    const del = (course) => {
      Confirm.show("删除后不可恢复，确认删除？", function () {
        Loading.show();
        axios.delete(process.env.VUE_APP_SERVER + "/business/admin/course/delete/" + course.id).then((response) => {
          const resp = response.data;
          if (resp.success) {
            //$('#form-modal').modal('hide');
            getCourseList(1);
          }
        })
        Toast.success("删除成功");
      })
    }

    // 添加课程
    const add = () => {
      // 新增课程 排序一次在总记录 递增
      course.value = {
        sort: paginationRef.value.total + 1,
      };
      tree.value.checkAllNodes(false);
      $('#form-modal').modal('show');
    }

    // 修改课程
    const edit = (param) => {
      // 方法一
      //course.value = JSON.parse(JSON.stringify(param));
      // 方法二
      listCategory(param.id)
      course.value = $.extend({}, param);
      $('#form-modal').modal('show');
    }

    // 渲染收费字段 收费 状态 级别
    const optionKV = (object, key) => {
      return Filter.optionKV(object, key);
    }

    // 跳转 至 大章
    const toChapter = (params) => {
      // 把course缓存起来
      SessionStorage.set(SESSION_KEY_COURSE, params);
      router.push("/business/chapter")
    }

    /**
     * 秒 的格式化 00:00:00
     * @param second
     */
    const formatSecond = (second) => {
      return Filter.formatSecond(second);
    }

    // 获取分类数据
    const allCategory = () => {
      axios.post(process.env.VUE_APP_SERVER + "/business/admin/category/all").then((response) => {
        const resp = response.data;
        categorys.value = resp.content;
        // 初始化 ztree
        initZTree();
      })
    }

    /**
     * 获取老师
     */
    const allTeacher = () => {
      axios.post(process.env.VUE_APP_SERVER + "/business/admin/teacher/all").then((response) => {
        const resp = response.data;
        teachers.value = resp.content;
      })
    }

    /**
     * 初始化树
     */
    const initZTree = () => {
      var setting = {
        check: {
          enable: true
        },
        data: {
          simpleData: {
            idKey: "id",
            pIdKey: "parent",
            rootPId: '00000000',
            enable: true
          }
        }
      };

      var zNodes = categorys.value;

      tree.value = $.fn.zTree.init($("#tree"), setting, zNodes);
    }

    /**
     * 跳转到 内容
     * @param course
     */
    const toContent = (course) => {
      SessionStorage.set(SESSION_KEY_COURSE, course);
      router.push("/business/content")
    }

    /**
     * 排序
     */
    const openSortModal = (course) => {
      // 打开模态框
      $('#course-sort-modal').modal('show');

      sort.value.oldValue = course.sort;
      sort.value.newValue = course.sort;
      sort.value.id= course.id;
    }

    /**
     * 更新排序
     */
    const updateSort = () => {
      if (sort.value.newValue === sort.value.oldValue) {
        Toast.warning("排序没有变化");
        return;
      }

      axios.post(process.env.VUE_APP_SERVER + "/business/admin/course/update-sort", sort.value)
      .then((response) => {
        const resp = response.data;
        if (resp.success) {
          getCourseList(1);
          // 关闭模态框
          $('#course-sort-modal').modal('hide');
          Toast.success("更新排序成功！");
        }else {
          Toast.error("更新排序失败!");
        }
      })
    }

    /**
     * 封面上传成功回调
     */
    const afterUpload = (file) => {
      course.value.image = file.path;
    }

    // 初始加载第一页
    onMounted(() => {
      getCourseList(1);
      COURSE_LEVEL_REF.value = COURSE_LEVEL;
      COURSE_CHARGE_REF.value = COURSE_CHARGE;
      COURSE_STATUS_REF.value = COURSE_STATUS;

      // 参数化 ztree
      allCategory();
      allTeacher();
    })

    return {
      courses,
      refresh,
      paginationRef,
      getCourseList,
      add,
      saveCourse,
      course,
      edit,
      del,
      COURSE_LEVEL_REF,
      COURSE_CHARGE_REF,
      COURSE_STATUS_REF,
      optionKV,
      toChapter,
      formatSecond,
      openSortModal,
      updateSort,
      sort,
      teachers,
      FILE_TYPE,
      afterUpload,
      toContent
    }
  }
}
</script>

<style scoped>
/*当屏幕像素小于1199px 课程名称字体变化*/
@media (max-width: 1199px) {
  .caption h3 {
    font-size: 16px;
  }
}
</style>